﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JustMathCore.AddrToolCoin
{
    class LTC : AddrTools.IAddrConv
    {
        public AddrTools.AddrType Type
        {
            get
            {
                return AddrTools.AddrType.LTC;
            }
        }
        static NBitcoin.Network main = NBitcoin.Network.Main;
        public string GetWif(byte[] prikey)
        {
            var key = new NBitcoin.Key(prikey);
            return key.GetWif(main).ToWif();
        }
        public byte[] GetHashAddr(byte[] prikey)
        {
            var key = new NBitcoin.Key(prikey);
            return key.GetAddress(NBitcoin.ScriptPubKeyType.Legacy, main).ScriptPubKey.ToBytes();//.GetDestination().ToBytes();
        }
        public string GetAddr(byte[] prikey)
        {
            var key = new NBitcoin.Key(prikey);
            return key.GetAddress(NBitcoin.ScriptPubKeyType.Legacy, main).ToString();
            //ScriptPubKey.GetDestinationAddress(main).ToString();
        }

        [ThreadStatic]
        static NBitcoin.DataEncoders.Base58CheckEncoder base58c;

        public byte[] Addr2Hash(string addr)
        {
            try
            {
                if (base58c == null)
                    base58c = new NBitcoin.DataEncoders.Base58CheckEncoder();
                return base58c.DecodeData(addr).Skip(1).ToArray();
            }
            catch(Exception err)
            {
                var baddr = NBitcoin.BitcoinAddress.Create(addr, main);
                return baddr.ScriptPubKey.ToBytes();
            }
        }
        //public void Addr2Hash(string addr, byte[] outdata, int outpos)
        //{
        //    if (base58c == null)
        //        base58c = new NBitcoin.DataEncoders.Base58CheckEncoder();
        //    var data = base58c.DecodeData(addr);
        //    for (var i = 0; i < 20; i++)
        //    {
        //        outdata[i + outpos] = data[i + 1];
        //    }
        //}
        public string Hash2Addr(byte[] hash)
        {
            if (base58c == null)
                base58c = new NBitcoin.DataEncoders.Base58CheckEncoder();
            return base58c.EncodeData(new byte[1] { 0x30 }.Concat(hash).ToArray());
        }

    }

}
